package experiment2;

import java.util.Random;

public class MergeArray {
 
    public static void main(String[] args) {
        MergeArray mergeArray = new MergeArray();
        int[] a1 = mergeArray.genArray(10);
        int[] a2 = mergeArray.genArray(10);
 
        mergeArray.sort(a1);
        mergeArray.sort(a2);
 
        int[] result = mergeArray.mergeArray(a1,a2);
        for(int i = 0; i < result.length; i++) {
            System.out.print(result[i] + " ");
        }
        System.out.println();
    }
 
    private void sort(int[] a) {
        for(int i = 0; i < a.length-1; i++) {
            for( int j = i+1; j < a.length; j++) {
                if(a[i] > a[j]) {
                    int tmp = a[i];
                    a[i] = a[j];
                    a[j] = tmp;
                }
            }
        }
    }
 
    private int[] mergeArray(int[] a1, int[] a2) {
        int s1 = a1.length;
        int s2 = a2.length;
        int[] a = new int[s1 + s2];
        int i = 0;
        int j = 0;
        int index = 0;
        while(i < s1 && j < s2) {
            if(a1[i] <= a2[j]) {
                a[index++] = a1[i];
                i++;
            } else {
                a[index++] = a2[j];
                j++;
            }
        }
 
        while(i < s1) {
            a[index++] = a1[i];
            i++;
        }
        while(j < s2) {
            a[index++] = a2[j];
            j++;
        }
        return a;
    }
 
    private int[] genArray(int n) {
        Random random = new Random();
        int[] as = new int[n];
        for(int i = 0; i < n; i++) {
            as[i] = random.nextInt(n);
        }
        return as;
    }
 
}
